package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.BusServiceItem;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.HistoricComment;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IBusServiceItemService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    @Lazy
    private IBusServiceItemService busServiceItemService;
    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream processImg(Long id) {
        //需要高亮的节点
        List<String> highLightedActivities = null;
        //需要高亮的连线
        List<String> highLightedFlows = Collections.EMPTY_LIST;
        CarPackageAudit audit = this.get(id);
        //判断流程是否已经结束
        String instanceId = audit.getInstanceId();
        String processDefinitionId = null;
        if(CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            //这个id是carPackageAudit的id,记录中只有instanceId.
            //通过instanceId找到流程实例对象. ===>流程定义对象
            ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(instanceId)
                    .singleResult();
            //获取到目前活动的节点
            highLightedActivities = runtimeService.getActiveActivityIds(instance.getId());
            processDefinitionId = instance.getProcessDefinitionId();
        }else{
            //获取历史流程实例
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(instanceId)
                    .singleResult();
            processDefinitionId = historicProcessInstance.getProcessDefinitionId();
            highLightedActivities = Collections.EMPTY_LIST;
        }
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model,highLightedActivities,highLightedFlows,"宋体","宋体","宋体");
    }

    @Override
    @Transactional
    public void cancelApply(Long id) {
        //合理性校验
        CarPackageAudit audit = this.get(id);
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("只有进行中的流程才能进行撤销");
        }
        //审核对象修改状态为流程撤销
        audit.setStatus(CarPackageAudit.STATUS_CANCEL);
        carPackageAuditMapper.updateByPrimaryKey(audit);
        //服务单项更新状态--->变成初始化状态
        busServiceItemService.changeStatus(audit.getServiceItemId(), BusServiceItem.AUDITSTATUS_INIT);
        //删除流程实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"流程撤销");
    }

    @Override
    public TablePageInfo<CarPackageAudit> todoQuery(CarPackageAuditQuery qo) {
        //根据套餐审核的下拉框value找到最新部署的流程定义的key
        BpmnInfo bpmnInfo = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();//套餐流程的key
        //查询符合条件的总数
        long count = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskAssignee(String.valueOf(ShiroUtils.getUserId()))
                .count();
        //如果总数为0,直接返回空集合
        if(count==0){
            return new TablePageInfo(0L,Collections.EMPTY_LIST);
        }
        //进行分页的查询
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskAssignee(String.valueOf(ShiroUtils.getUserId()))
                .listPage((qo.getPageNum() - 1) * qo.getPageSize(), qo.getPageSize());
        List<String> businessKeyList = new ArrayList<>();
        //遍历任务
        for(Task task:tasks){
            //根据任务查询流程实例对象
            ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            //通过流程实例对象获取businessKey,存储到集合中
            businessKeyList.add(instance.getBusinessKey());
        }
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.queryTaskList(businessKeyList);
        return new TablePageInfo<CarPackageAudit>(count,carPackageAudits);
    }

    @Override
    @Transactional
    public void audit(Long id, String auditStatus, String info) {
        CarPackageAudit audit = this.get(id);
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("只有进行中的流程才能进行审批操作");
        }
        Boolean status = Boolean.valueOf(auditStatus);
        //通过流程实例ID查询任务
        String instanceId = audit.getInstanceId();
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(instanceId)
                .singleResult();
        //设置批注信息
        String message = ShiroUtils.getUser().getUserName()+(status?"[同意]":"[拒绝]")+",审批意见:"+info;
        taskService.addComment(currentTask.getId(),instanceId,message);
        // currentTask.getTaskDefinitionKey()===>获取到节点在流程图中定义的id
        String taskDefinitionKey = currentTask.getTaskDefinitionKey();
        //设置流程变量
        Map<String,Object> variables = new HashMap<>();
        variables.put(taskDefinitionKey,status);
        //完成任务
        taskService.complete(currentTask.getId(),variables);
        //********************************************************************************
        if(status){
            //审核人选择同意
            //判断流程是否结束?查看是否有下一个任务
            Task nextTask = taskService.createTaskQuery()
                    .processInstanceId(instanceId)
                    .singleResult();
            if(nextTask==null){
                //流程走完了.
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                carPackageAuditMapper.updateByPrimaryKey(audit);
                //服务单项状态--->审核通过
                busServiceItemService.changeStatus(audit.getServiceItemId(),BusServiceItem.AUDITSTATUS_APPROVED);
            }
        }else{
            //审核人选择拒绝
            //修改审核对象的状态---->审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            carPackageAuditMapper.updateByPrimaryKey(audit);
            //服务单项状态--->重新调整
            busServiceItemService.changeStatus(audit.getServiceItemId(),BusServiceItem.AUDITSTATUS_REPLY);
        }
    }

    @Override
    public TablePageInfo<CarPackageAudit> doneQuery(CarPackageAuditQuery qo) {
        //获取部署的流程定义信息
        BpmnInfo bpmnInfo = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
        //流程定义的key
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        long count = historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(processDefinitionKey)//只查询套餐审核的历史
                .taskAssignee(String.valueOf(ShiroUtils.getUserId()))//查询谁的记录
                .finished()//已经完成的任务
                .count();
        if(count==0){
            return new TablePageInfo(0L,Collections.EMPTY_LIST);
        }
        //查询历史任务的集合
        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(processDefinitionKey)//只查询套餐审核的历史
                .taskAssignee(String.valueOf(ShiroUtils.getUserId()))//查询谁的记录
                .finished()
                .listPage((qo.getPageNum() - 1) * qo.getPageSize(), qo.getPageSize());
        List<String> businessKeyList = new ArrayList<>();
        //遍历获取业务Key
        for(HistoricTaskInstance task:historicTaskInstances){
            //获取历史流程实例
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()//查询所有历史的流程实例对象
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            String businessKey = historicProcessInstance.getBusinessKey();
            businessKeyList.add(businessKey);

        }
        List<CarPackageAudit> carPackageAuditList =carPackageAuditMapper.queryTaskList(businessKeyList);
        return new TablePageInfo<>(count,carPackageAuditList);
    }

    @Override
    public TablePageInfo<HistoricComment> historyListQuery(String instanceId) {
        List<HistoricComment> commentList = new ArrayList<>();
        //根据流程实例ID查询历史的任务审批信息
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(instanceId)//查询这个流程实例的历史任务集合
                .finished()//已经完成的
                .orderByTaskCreateTime()//对任务创建时间进行排序
                .desc()//进行降序排序
                .list();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(HistoricTaskInstance task:taskList){
            HistoricComment comment = new HistoricComment();
            comment.setTaskName(task.getName());
            comment.setStartTime(sdf.format(task.getStartTime()));
            comment.setEndTime(sdf.format(task.getEndTime()));
            comment.setDurationInMillis(String.valueOf(task.getDurationInMillis()));
            List<Comment> taskComments = taskService.getTaskComments(task.getId());//获取任务批注信息
            if(taskComments.size()>0){
                //设置批注信息
                comment.setComment(taskComments.get(0).getFullMessage());
            }
            commentList.add(comment);
        }
        return new TablePageInfo(Long.valueOf(commentList.size()),commentList);
    }
}
